package org.eduapp.trains.web.action.train;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.eduapp.trains.Constants;
import org.eduapp.trains.ServiceException;
import org.eduapp.trains.model.train.ModelTrain;
import org.eduapp.trains.service.train.TrainService;
import org.eduapp.trains.utils.UtilsString;
import org.eduapp.trains.vo.VoTrainSearch;
import org.eduapp.trains.web.action.BaseAction;

public class TrainAction extends BaseAction {

	private final static Logger logger = Logger.getLogger(TrainAction.class);

	private TrainService trainService;

	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward trainSearchIndex (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		if (UtilsString.isNotEmpty(request.getParameter("search"))) {

			//VoTrainSearch voForm = (VoTrainSearch) form;
			
			ModelTrain modelTrain = (ModelTrain) form;
			VoTrainSearch voForm = modelTrain.getTrainSearchVO();
			
			if (voForm == null) {
				return mapping.findForward("error");
			}
			
			if (UtilsString.isNotEmpty(voForm.getTrainNumber())) {
				// 車次查詢
				return new ActionForward("/app/train/search?code=" + voForm.getTrainNumber().trim(), true);
			} else if (UtilsString.isNotEmpty(voForm.getTrainStationFrom()) && 
					UtilsString.isNotEmpty(voForm.getTrainStationTo())) {
				// 站站查詢
				try {
					return new ActionForward(
							"/app/train/search?from=" + 
								URLEncoder.encode(voForm.getTrainStationFrom().trim(), "UTF-8") + "&to=" +
								URLEncoder.encode(voForm.getTrainStationTo().trim(), "UTF-8"), true);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			} else if (UtilsString.isNotEmpty(voForm.getTrainStationName())) {
				// 車站查詢
				try {
					return new ActionForward("/app/train/search?station=" +
						URLEncoder.encode(voForm.getTrainStationName().trim(), "UTF-8"), true);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			} else {
				return new ActionForward("/app/train/search?station=", true);
			}
		}
		
		return mapping.findForward("index");
	}

	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward trainSearchView(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		ModelTrain modelTrain = (ModelTrain) form;
		VoTrainSearch voSearch = modelTrain.getTrainSearchVO();
		
		String from = voSearch.getTrainStationFrom();
		String to   = voSearch.getTrainStationTo();
		String name = voSearch.getTrainStationName();
		try{
			if(from!=null&&!from.matches("[\\u4E00-\\u9FA5]+")){
				voSearch.setTrainStationFrom(new String(from.getBytes("ISO-8859-1"),"GBK"));
			}
			if(to!=null&&!to.matches("[\\u4E00-\\u9FA5]+")){
				voSearch.setTrainStationTo(new String(to.getBytes("ISO-8859-1"),"GBK"));
			}
			if(name!=null&&!name.matches("[\\u4E00-\\u9FA5]+")){
				voSearch.setTrainStationName(new String(name.getBytes("ISO-8859-1"),"GBK"));
			}
			if(name!=null&&!voSearch.getTrainStationName().matches("[\\u4E00-\\u9FA5]+")){
				voSearch.setTrainStationName(new String(name.getBytes("ISO-8859-1"),"UTF-8"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		if (voSearch == null) {
			return mapping.findForward("error");
		}
		
		//VoTrainSearch voSearch = (VoTrainSearch) form;

		boolean success = true;
		
		if (voSearch != null) {
			
			int page = request.getParameter(Constants.DefaultPageParamFlag) == null ? 1 : 
				Integer.parseInt(request.getParameter(Constants.DefaultPageParamFlag));
			
			int offset = (page - 1) * Constants.DefaultPageSize;

			voSearch.setTrainOffset(offset);

			try {
				request.setAttribute("result.page", trainService
						.getBySearchVO(voSearch));
				//request.setAttribute("search_type", voSearch.getTrainSearchType());
				request.setAttribute("search_vo", voSearch);
				request.setAttribute("query.link", voSearch.getQuery());
				request.setAttribute("page", page);
			} catch (ServiceException e) {
				success = false;
				logger.error(e);
				e.printStackTrace();
			}
		}
		
		request.setAttribute("nav_code", "search");
		
		return success ? (
				isAjaxReq(request) ? mapping.findForward("ajax_data") : mapping.findForward("success")) : mapping.findForward("error");

	}

	public void setTrainService(TrainService trainService) {
		this.trainService = trainService;
	}

	public TrainService getTrainService() {
		return trainService;
	}

	public static Logger getLogger() {
		return logger;
	}
}
